<?php

class WSB_View_Helper_PageSelect
{

	private static $_instance = 0;
    private $_url;
    private $_id;
    private $_html;

    public function pageSelect($url, $id)
	{
    	self::$_instance++;
    	$this->_html = '';
        $this->_url = $url;
        $this->_id = $id;
		$node = WSB_Node_Page::getTree();
		$this->_buildOptions($node);
		return sprintf(
            '<script type="text/javascript">
                var url = \'%1$s\';
                function pageSelectJumpUrl%3$s(id)
	{
                    window.location.href=url.replace(\'#\', id);
                }
            </script>
            <select onchange="pageSelectJumpUrl%3$s(this.options[this.selectedIndex].value);">%2$s</select>',
            $this->_url,
            $this->_html,
            self::$_instance
        );
    }

    private function _buildOptions(WSB_Node_Page $node)
	{
        if(!$node->hasParent()) {
            $this->_html .= $this->_buildOption($node);
        }
        foreach($node->getChildren() AS $child) {
            $this->_html .= $this->_buildOption($child);
            if($child->hasChildren()) {
                $this->_buildOptions($child);
            }
        }
    }

    private function _buildOption(WSB_Node_Page $node)
	{
    	$id = $node->getPageId();
		$delim = ' &rsaquo; ';

		// Traversiere Baum bis zur Wurzel
       	$i = 0;
    	$segments = array();
    	while(!$node->isRoot()) {
    		array_unshift($segments, $node->title);
    		$node = $node->getParent();
    		$i++;
    		if($i > 100) die('Error in WSB_View_Helper_PageSelect: endless loop');
    	}
    	array_unshift($segments, $node->title);

        return sprintf('<option value="%s"%s>%s</option>', $id, ($id == $this->_id) ? ' selected="selected"' : '', implode($delim, $segments));
    }

}
